/*
 * MIT License
 * Copyright (c) 2021 -- wangxiaozhe
 */
package com.pearadmin.pro.common.tools.core;

import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @author wangxiaozhe
 */
@Slf4j
public class CmdUtil {

    public static String exec(String command) throws IOException, InterruptedException {
        Process proc = Runtime.getRuntime().exec(command);
        //获取脚本执行的得到的结果并缓存
        BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        StringBuilder result = new StringBuilder();
        String str;
        //读取数据
        while ((str = reader.readLine()) != null) {
            result.append(str);//打印结果
        }
        reader.close();
        proc.waitFor();
        log.info(result.toString());
        return result.toString();
    }

    public static List<SoftwareStatus> execMacStatus() throws IOException, InterruptedException {
        String result = CmdUtil.exec("brew services");
        String[] res = result.split("\\s+");
        List<String> list = Arrays.asList(res).subList(3, res.length);
        List<SoftwareStatus> rlist = new ArrayList();
        for (int i = 0; i < list.size() - 1; i++) {
            SoftwareStatus ss = new SoftwareStatus();
            String key = "", value = "";
            if (i % 2 == 0) {
                key = list.get(i);
                value = list.get(++i);
                ss.setName(key);
                ss.setStatus(value);
                rlist.add(ss);
            }
        }
        log.info(rlist.toString());
        return rlist;
    }

}

@Data
@ToString
class SoftwareStatus {
    String name;
    String status;
}
